package cn.xenosp.server.module.scheduler.entity;

import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.annotation.*;

import java.io.Serializable;
import java.time.LocalDateTime;
import java.util.Date;
import lombok.Data;

/**
 * 任务执行日志表
 * @TableName scheduler_task_log
 */
@TableName(value ="scheduled_task_log")
@Data
public class ScheduledTaskLog implements Serializable {
    /**
     * 日志ID，UUID
     */
    @TableId(value = "id")
    private String id;

    /**
     * 任务ID
     */
    @TableField(value = "task_id")
    private String taskId;

    /**
     * 任务名称
     */
    @TableField(value = "task_name")
    private String taskName;

    /**
     * 开始时间
     */
    @TableField(value = "start_time")
    private Date startTime;

    /**
     * 结束时间
     */
    @TableField(value = "end_time")
    private Date endTime;

    /**
     * 执行状态：RUNNING-执行中，SUCCESS-成功，FAILED-失败
     */
    @TableField(value = "status")
    private String status;

    /**
     * 错误信息
     */
    @TableField(value = "error_message")
    private String errorMessage;

    /**
     * 执行耗时（毫秒）
     */
    @TableField(value = "execution_time")
    private Long executionTime;

    /**
     * 执行结果
     */
    @TableField(value = "result")
    private String result;

    /**
     * 控制台日志
     */
    @TableField(value = "console_log")
    private String consoleLog;

    /**
     * 创建者
     */
    @TableField(value = "creator",fill= FieldFill.INSERT)
    private String creator;

    /**
     * 创建时间
     */
    @TableField(value = "create_time",fill= FieldFill.INSERT)
    private Date createTime;

    /**
     * 更新者
     */
    @TableField(value = "updater",fill= FieldFill.INSERT_UPDATE)
    private String updater;

    /**
     * 更新时间
     */
    @TableField(value = "update_time",fill= FieldFill.INSERT_UPDATE)
    private Date updateTime;

    /**
     * 是否删除
     */
    @TableField(value = "deleted")
    private Boolean deleted;

    @TableField(exist = false)
    private static final long serialVersionUID = 1L;


    // 构造函数
    public ScheduledTaskLog() {

    }

    public ScheduledTaskLog(String taskId, String taskName) {
        this.taskId = taskId;
        this.taskName = taskName;
        this.startTime = DateUtil.date();
        this.status = "RUNNING";
    }

    // 标记执行完成
    public void markSuccess(String result) {
        this.endTime = DateUtil.date();
        this.status = "SUCCESS";
        this.result = result;
        this.executionTime = DateUtil.between(startTime, endTime, DateUnit.MS);
    }

    // 标记执行失败
    public void markFailed(String errorMessage) {
        this.endTime = DateUtil.date();
        this.status = "FAILED";
        this.errorMessage = errorMessage;
        this.executionTime = DateUtil.between(startTime, endTime, DateUnit.MS);
    }
}